package org.ciallo.simplemusicplayer.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.activity.AlbumSongsActivity;
import org.ciallo.simplemusicplayer.adapter.AlbumAdapter;
import org.ciallo.simplemusicplayer.viewmodel.LocalMusicViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.Locale;

/**
 * @author Jukomu
 * @Description: 显示专辑列表的Fragment
 * @Package: org.ciallo.simplemusicplayer.fragment
 * @Project: SimpleMusicPlayer
 * @name: AlbumListFragment
 * @Date: 2025/6/2-23:31
 * @Filename: AlbumListFragment
 */
public class AlbumListFragment extends Fragment {
    private RecyclerView recyclerViewAlbums;
    private AlbumAdapter albumAdapter;
    private LocalMusicViewModel localMusicViewModel;
    private TextView tvEmptyList;
    private SwipeRefreshLayout swipeRefreshLayout;
    private SharedViewModel sharedViewModel;
    private TextView tvArtistSearchLabel; // <--- (可选) 添加搜索结果提示标签

    public AlbumListFragment() {
// Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
// 复用 fragment_generic_list.xml 布局
        return inflater.inflate(R.layout.fragment_generic_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);

        localMusicViewModel = new ViewModelProvider(requireActivity()).get(LocalMusicViewModel.class);

        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout_generic_list);
        recyclerViewAlbums = view.findViewById(R.id.recyclerView_generic);
        tvEmptyList = view.findViewById(R.id.textView_empty_list);
        tvEmptyList.setText("没有找到专辑信息"); // 设置空状态提示

        setupRecyclerView();
        setupSwipeRefreshLayout();
        observeViewModel();
    }

    private void setupRecyclerView() {
        albumAdapter = new AlbumAdapter(albumInfo -> {
            // 点击专辑，跳转到该专辑的歌曲列表页面
            Intent intent = new Intent(getActivity(), AlbumSongsActivity.class);
            intent.putExtra(AlbumSongsActivity.EXTRA_ALBUM_ID, albumInfo.albumId);
            intent.putExtra(AlbumSongsActivity.EXTRA_ALBUM_NAME, albumInfo.albumName);
            intent.putExtra(AlbumSongsActivity.EXTRA_ALBUM_ARTIST_NAME, albumInfo.artistName); // 传递专辑艺术家
            intent.putExtra(AlbumSongsActivity.EXTRA_ALBUM_ART_URI, albumInfo.albumArtUri); // 传递封面
            startActivity(intent);
        });
        // 专辑列表通常用网格布局更好看，例如2列或3列
        recyclerViewAlbums.setLayoutManager(new GridLayoutManager(getContext(), 2));
        // 或者如果你喜欢列表样式：
        // recyclerViewAlbums.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewAlbums.setAdapter(albumAdapter);
    }

    private void setupSwipeRefreshLayout() {
        swipeRefreshLayout.setOnRefreshListener(() -> {
            Timber.d("AlbumListFragment: Swipe to refresh triggered.");
            localMusicViewModel.startMediaStoreScan(); // 刷新同样是触发歌曲扫描
        });
        if (getContext() != null) {
            swipeRefreshLayout.setColorSchemeColors(
                    ContextCompat.getColor(getContext(), R.color.md_theme_light_primary),
                    ContextCompat.getColor(getContext(), R.color.md_theme_light_secondary)
            );
        }
    }

    private void observeViewModel() {
        // 1. 观察全局搜索查询词
        sharedViewModel.currentSearchQuery.observe(getViewLifecycleOwner(), query -> {
            Timber.d("AlbumListFragment: Observed global search query: '%s'", query);
            localMusicViewModel.updateSearchQuery(query);

            // (可选) 更新此Fragment的搜索结果提示标签
            // if (tvAlbumSearchLabel != null) {
            //     if (query != null && !query.trim().isEmpty()) {
            //         tvAlbumSearchLabel.setText(String.format(Locale.getDefault(), "“%s”的专辑搜索结果：", query.trim()));
            //         tvAlbumSearchLabel.setVisibility(View.VISIBLE);
            //     } else {
            //         tvAlbumSearchLabel.setVisibility(View.GONE);
            //     }
            // }
        });

        // 2. 观察扫描状态
        localMusicViewModel.isScanning.observe(getViewLifecycleOwner(), isScanning -> {
            if (swipeRefreshLayout != null) swipeRefreshLayout.setRefreshing(isScanning);
        });

        // 3. 观察最终要显示的专辑列表
        localMusicViewModel.albumsToDisplay.observe(getViewLifecycleOwner(), albums -> {
            Timber.d("AlbumListFragment: albumsToDisplay updated. Count: %d", albums != null ? albums.size() : 0);
            Boolean isLoading = localMusicViewModel.isScanning.getValue();
            String currentQuery = sharedViewModel.currentSearchQuery.getValue();
            boolean searchActive = currentQuery != null && !currentQuery.trim().isEmpty();

            if (albums != null && !albums.isEmpty()) {
                albumAdapter.submitList(new ArrayList<>(albums));
                tvEmptyList.setVisibility(View.GONE);
                recyclerViewAlbums.setVisibility(View.VISIBLE);
            } else {
                albumAdapter.submitList(new ArrayList<>());
                recyclerViewAlbums.setVisibility(View.GONE);
                if (isLoading == null || !isLoading) {
                    if (searchActive) {
                        tvEmptyList.setText(String.format(Locale.getDefault(), "没有找到与“%s”相关的专辑", currentQuery != null ? currentQuery.trim() : ""));
                    } else {
                        tvEmptyList.setText("没有找到专辑信息");
                    }
                    tvEmptyList.setVisibility(View.VISIBLE);
                } else {
                    tvEmptyList.setVisibility(View.GONE);
                }
            }
        });
    }
}
